<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>首页</title>
  <link rel="stylesheet" href="./css/index.css">
  <script src="./js/cookie.js"></script>
  <script src="./js/requset.js"></script>
</head>

<body>
  <div class="top">
    <a href="/login.html">登录</a>
    <a href="/register.html">注册</a>
  </div>
  <div class="t">
    <ul>

    </ul>
  </div>
  <script>
    const top_ = document.querySelector('.top')
    const t = document.querySelector('.t ul')
    const username = getCookie('username')
    // console.log(username);
    if (username) {
      top_.innerHTML = `
      <a href="/login.html">欢迎</a>
      <b><a href="/usercenter.html" style="color: red;">${username}</a></b>
      <a href="javascript:;"onclick="logout()">退出</a>
      `
    }
    //退出逻辑
    function logout() {
      if (confirm('你确定要退出吗？')) {
        removeCookie('username')
        removeCookie('userid')
        //清除令牌
        localStorage.removeItem('token')
        top_.innerHTML = `
          <a href="/login.html">登录</a>
          <a href="/register.html">注册</a>
      `
      }
    }
    //页码
    let page = 1
    // 数据条数
    let pagesize = 20
    let flag = true
    req()
    function req() {
      if (!flag) return
      flag = false
      // console.log(page);
      request({
        url: `/goods/api/goodslist/${page}/${pagesize}`,
      }).then((res) => {
        // console.log(res);
        //ajax获取到数据后渲染
        var data = res.data.data
        //没有数据跳出
        if (data.length === 0) {
          return
        }
        //ajax获取到数据后渲染
        var html = ''
        data.forEach(goods => {
          html += `
                <a href="detail.html?id=${goods._id}" style="display: block;width: 100%; height: 100%;">
                    <li>
                      <div class="package">
                        <img src="${goods.img_big_logo}" alt="">
                        <div class="tite">
                          ${goods.title}
                        </div>
                        <div class="pricee">
                          价格：${goods.price}
                        </div>
                        <div>
                    </li>
                </a>
            `
        })
        t.innerHTML += html
        page++
        flag = true
      })
    }
    var windowTop = document.querySelector('.top')
    var windowt = document.querySelector('.t')
    window.onscroll = function () {
      var h = document.documentElement.scrollTop || document.body.scrollTop
      // 当卷去的距离 + 浏览器高度 > 当前文档的高度的时候
      // console.log(h + innerHeight);
      // console.log(windowTop.offsetHeight + windowt.offsetHeight -900);
      if (h + innerHeight > windowTop.offsetHeight + windowt.offsetHeight - 500) {
        req()
      }
    }
  </script>
</body>

</html>